class MembershipsController < ApplicationController
  
  before_filter :login_required, :except => 'new'
  before_filter :identify_group, :except => 'new'
  
  # GET /memberships
  # GET /memberships.xml
  def index
    @memberships = @group.memberships

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @memberships }
    end
  end

  # GET /memberships/1
  # GET /memberships/1.xml
  def show
    @membership = Membership.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @membership }
    end
  end

  # GET /memberships/new
  # GET /memberships/new.xml
  def new
    @membership = Membership.new
    @invitation = Invitation.find_by_key(params[:id])
    session[:invitation_id] = @invitation.id
    
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @membership }
    end
  end

  # GET /memberships/1/edit
  def edit
    @membership = Membership.find(params[:id])
  end

  # POST /memberships
  # POST /memberships.xml
  def create
    @membership = Membership.new(params[:membership])
    @invitation = Invitation.find(session[:invitation_id])
    
    @membership.group = @invitation.group
    @membership.user = current_user
    @membership.role = Role.find_by_rolename('player')
    
    respond_to do |format|
      if @membership.save
        session[:key] = nil
        @invitation.destroy
        
        flash[:notice] = 'Membership was successfully created.'
        format.html { redirect_to(@group) }
        format.xml  { render :xml => @membership, :status => :created, :location => @membership }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @membership.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /memberships/1
  # PUT /memberships/1.xml
  def update
    @membership = Membership.find(params[:id])

    respond_to do |format|
      if @membership.update_attributes(params[:membership])
        flash[:notice] = 'Membership was successfully updated.'
        format.html { redirect_to(@group) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @membership.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /memberships/1
  # DELETE /memberships/1.xml
  def destroy
    @membership = Membership.find(params[:id])
    @membership.destroy

    respond_to do |format|
      format.html { redirect_to(@group) }
      format.xml  { head :ok }
    end
  end
  
  private
  
  def identify_group
    @group = Group.find(params[:group_id])
  end
  
end
